// https://leetcode.cn/problems/sum-of-root-to-leaf-binary-numbers/
// Created by ade on 2022/10/25.
//

/**
 * Definition for a binary tree node.
 * */
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;

    TreeNode() : val(0), left(nullptr), right(nullptr) {}

    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}

    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

class Solution {
public:
    int sum = 0;

    int sumRootToLeaf(TreeNode *root) {
        dfs(root, 0);
        return sum;
    }

    void dfs(TreeNode *root, int tmp) {
        tmp = tmp * 2 + root->val;
        if (root->left)
            dfs(root->left, tmp);
        if (root->right)
            dfs(root->right, tmp);
        if(!root->left && !root->right){
            sum += tmp;
        }
    }
};